//
//  EmojiView.m
//  Custom_Weibo
//
//  Created by LEO on 12/21/15.
//  Copyright © 2015 Leo_Lei. All rights reserved.
//

#import "EmojiView.h"

@implementation EmojiView

#pragma mark - INITIALIZATION_METHODS
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self loadData];
    }
    return self;
}

- (NSInteger)pageNumber {
    return _pageArray.count;
}

#pragma mark - LOAD_DATA
- (void)loadData {
    /*  This array is two-dimensional for saving one-dimensional array.The 
     number of one-dimensional array depends on the pages for emoji total counts.
     */
    _pageArray = [[NSMutableArray alloc] init];
    
    //  1)Get all the emoji information, and put them into one-dimensional array.
    NSString *filePath = [[NSBundle mainBundle] pathForResource:kEmojiFileName ofType:nil];
    NSArray *emotiIcons = [NSArray arrayWithContentsOfFile:filePath];
    
    //  2)Add all the one-dimensional array into two-dimensional array.
    NSInteger maxEmojiOfEachPage = kRowsOfEmoji * kQueuesOfEmoji;
    
    NSInteger pageNumber = emotiIcons.count / maxEmojiOfEachPage;
    if (emotiIcons.count % maxEmojiOfEachPage != 0) {
        pageNumber = pageNumber + 1;
    }
    
    for (NSInteger i = 0; i < pageNumber; i++) {
        NSInteger emojiOfEachPage = emotiIcons.count - i * maxEmojiOfEachPage;
        NSRange range = NSMakeRange(i * maxEmojiOfEachPage, maxEmojiOfEachPage);
        if (emojiOfEachPage < maxEmojiOfEachPage) {
            //  Emoji shows on the last page.
            range = NSMakeRange(i * maxEmojiOfEachPage, emojiOfEachPage);
        }
        NSArray *array2D = [emotiIcons subarrayWithRange:range];
        [_pageArray addObject:array2D];
    }
    
    self.height = kEmojiViewHeight * kRowsOfEmoji;
    self.width = kScreenWidth * pageNumber;
    
    //  3)Create a magnify view.
    CGRect magnifierFrame = CGRectMake(0, 0,
                                       kNavigationBarHeight,
                                       kNavigationBarHeight + maxEmojiOfEachPage);
    
    _magnifierView = [[UIImageView alloc] initWithFrame:magnifierFrame];
    _magnifierView.image = [UIImage imageNamed:@"emoticon_keyboard_magnifier"];
    _magnifierView.backgroundColor = [UIColor clearColor];
    _magnifierView.hidden = YES;
    [self addSubview:_magnifierView];
    
    //  Show the selected emoji.
    CGRect selectedFrame = CGRectMake(
                                      (_magnifierView.width - kEmojiWidth * kEmojiZoomScale) / 2,
                                      9,    //  '9' here is customized by myself.
                                      kEmojiWidth * kEmojiZoomScale,
                                      kEmojiHeight * kEmojiZoomScale
                                      );
    
    UIImageView *emojiImageView = [[UIImageView alloc] initWithFrame:selectedFrame];
    emojiImageView.backgroundColor = [UIColor clearColor];
    emojiImageView.tag = kEmojiTag;
    [_magnifierView addSubview:emojiImageView];
}

#pragma mark DRAW_EMOJI
- (void)drawRect:(CGRect)rect {
    for (NSInteger i = 0; i < _pageArray.count; i++) {
        //  Saving each page's emoji.
        NSArray *item2D = _pageArray[i];
        for (NSInteger j = 0; j < item2D.count; j++) {
            //  1)Get the emoji from its dictionary.
            NSDictionary *item = item2D[j];
            NSString *imageName = item[@"png"];
            UIImage *image = [UIImage imageNamed:imageName];
            
            //  2)Calculate its position.
            NSInteger row = j / kQueuesOfEmoji;
            NSInteger queue = j % kQueuesOfEmoji;
            
            CGFloat x = queue * kEmojiViewWidth + (kEmojiViewWidth - kEmojiWidth) / 2 + kScreenWidth * i;
            CGFloat y = row * kEmojiViewHeight + (kEmojiViewHeight - kEmojiHeight) / 2;
            
            CGRect imageFrame = CGRectMake(x, y, kEmojiWidth, kEmojiHeight);
            
            //  3)Draw emoji.
            [image drawInRect:imageFrame];
        }
        
    }
}

#pragma mark - TOUCH_EMOJI
- (void)touchEmoji:(CGPoint)point {
    //  1)First, we should know it is located in which page.
    NSInteger atPage = point.x / kScreenWidth;
    
    //  2)Second, we should know its accurate position.
    NSInteger row = (point.y - (kEmojiViewHeight - kEmojiHeight) / 2) / kEmojiViewHeight;
    NSInteger queue = (point.x - ((kEmojiViewWidth - kEmojiWidth) / 2 + atPage * kScreenWidth)) / kEmojiViewWidth;
    
    //  3)Fix problem when choose max count of emoji.
    if (row < 0) {
        row = 0;
    }
    if (row > 3) {
        row = 3;
    }
    
    if (queue < 0) {
        queue = 0;
    }
    if (queue > 6) {
        queue = 6;
    }
    
    //  4)Find emoji throgh target queue and row.
    NSArray *item2D = [_pageArray objectAtIndex:atPage];
    NSInteger index = row * kQueuesOfEmoji + queue;
    if (index >= item2D.count) {
        return;
    }
    
    //  5)Get the emoji.
    NSDictionary *item = [item2D objectAtIndex:index];
    
    NSString *imageName = [item objectForKey:@"png"];
    NSString *wordsName = [item objectForKey:@"chs"];
    
    if (![_selectedEmojiName isEqualToString:wordsName]) {
        _selectedEmojiName = wordsName;
        
        CGFloat x = queue * kEmojiViewWidth + atPage * kScreenWidth + kEmojiViewWidth / 2;
        CGFloat y = row * kEmojiViewHeight + kEmojiViewHeight / 2;
        
        _magnifierView.center = CGPointMake(x, 0);
        _magnifierView.bottom = y;
        
        UIImageView *emojiImageView = (UIImageView *)[_magnifierView viewWithTag:kEmojiTag];
        emojiImageView.image = [UIImage imageNamed:imageName];
    }
}

#pragma mark UITOUCH_METHODS
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //  Show the magnifier view when finger pressed.
    _magnifierView.hidden = NO;
    
    /*  When users select an emoji, if there is a scroll view on the emoji, then
     we should set the scroll view unable to scroll.
     */
    if ([self.superview isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollView = (UIScrollView *)self.superview;
        scrollView.scrollEnabled = NO;
    }
    
    //  Get the touch point
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    
    //  When user touch the screen, try to know which emoji did user choose.
    [self touchEmoji:point];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    /*  When users drag their finger pass one to another emoji, it will do the
     same as showing the emoji.
     */
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    
    [self touchEmoji:point];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //  When user's finger away from screen, we should make the magnifier unvisible.
    _magnifierView.hidden = YES;
    
    //  Also, we should let the scroll view on the emoji able to scroll again.
    if ([self.superview isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollView = (UIScrollView *)self.superview;
        scrollView.scrollEnabled = YES;
    }
    
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    
    [self touchEmoji:point];
    
    if ([_delegate respondsToSelector:@selector(emojiDidSelect:)]) {
        [_delegate emojiDidSelect:_selectedEmojiName];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
